<template>

    <div id="dashboard">
        <vHeadSpace />
        <div class="outcontainer">
            <vAsideSpace />
            <div  class="content" style="margin-left: 25px;margin-right: 25px;margin-top: 25px">
                <h4 style="text-align: left">主机管理</h4>
                <!-- 筛选条件这一栏 -->
                <!--        <el-row>-->
                <!--            <el-col :span="2">-->
                <!--                <el-button type="primary" icon="el-icon-switch-button" @click="shutdownHost">关机</el-button>-->
                <!--            </el-col>-->
                <!--            <el-col :span="2">-->
                <!--                <el-button type="primary" icon="el-icon-refresh-left">重启</el-button>-->
                <!--            </el-col>-->
                <!--        </el-row>-->
                <!-- 主机列表 -->
                <el-col :span="8">
                    <div class="filter-container">
                        <label>查询主机:</label>
                        <el-input v-model="queryString" placeholder="设备名称" style="width: 200px;margin-left: 3px;margin-right: 5px;margin-top: 12px;" class="filter-item" />
                    </div>
                </el-col>
                <el-table
                        v-loading="pictLoading"
                        :data="handleInput()"
                        ref="hostList"
                        tooltip-effect="dark"
                        style="width: 100%"
                        element-loading-text="数据正在加载中"
                >
                    <!-- 选择框 -->
                    <!--            <el-table-column type="selection" align="center" width="55"></el-table-column>-->
                    <el-table-column width="60px" align="center" prop="sequence" label="序号">
                        <template slot-scope="scope">
                            {{ (currentPage - 1) * pageNum + scope.$index + 1 }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="name" label="主机名称" width="800px" align="center"></el-table-column>
                    <el-table-column prop="operator" label="操作" align="center">
                        <template slot-scope="scope">
                            <el-button type="text" icon="el-icon-switch-button" @click="closeHost(scope.row)">关机</el-button>
                            <el-button type="text" icon="el-icon-refresh-left" @click="rebootHost(scope.row)">重启</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <!--分页控件-->
                <el-pagination
                        :current-page="currentPage"
                        :page-sizes="[10,20,30,40]"
                        :page-size="100"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="totalNum"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                />

                <!--让用户输入想要操作的主机的账号和密码-->
                <el-dialog
                        title="请输入该主机的账号和密码"
                        :visible.sync="dialogVisible"
                        width="30%"
                >
                    <!-- 输入账号 -->
                    <el-row>
                        <el-col :span="3" style="padding-top: 10px"><label>账号：</label></el-col>
                        <el-col :span="20"><el-input v-model="hostAccount" placeholder="请输入账号"></el-input></el-col>
                    </el-row>
                    <br/>
                    <!-- 输入密码 -->
                    <el-row>
                        <el-col :span="3" style="padding-top: 10px"><label>密码：</label></el-col>
                        <el-col :span="20"><el-input v-model="hostPassword" show-password placeholder="请输入密码"></el-input></el-col>
                    </el-row>

                    <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="operateCode == '0'?postShutdownRequest():postRebootRequest()">确 定</el-button>
            </span>
                </el-dialog>
            </div>
        </div>
        <vFootSpace />

    </div>



</template>

<script>
    import axios from "axios";

    export default {
        name: "HostManagement",
        data() {
            return {
                online_host_list: [],
                hostId: '',    //主机名称
                tableData: [], // 表格内部的数据
                pictLoading: false,  //加载项
                currentPage: 1,   //当前页面
                pageNum: 10, // 每页展示多少数据
                totalNum: 0, // 数据总条数
                dialogVisible: false, // 对话框的可见性
                operatedId: '', // 操作主机的ID
                hostAccount: '', // 要操作的主机的账号
                hostPassword: '', // 要操作的主机的密码
                operateCode:"0", //0表示关机，1表示重启
                queryString: '', // 查询主机
                options: {
                    pagination: true,
                    pageSize: 7,
                    pageList: [5, 10, 20]
                },
            }
        },
        methods: {
            sizeChange(val) {
                this.currentPage = 1
                this.pageSize = val
            },
            currentChange: function (currentPage) {
                this.currentPage = currentPage
            },
            // 设置总的数量
            setTotalNum(){
                const _this = this;
                axios({
                    method: 'get',
                    url: '/demo/get_all_online_host.action',
                }).then((res) => {
                    let result = res.data.content.result; // 获取所有的主机
                    _this.totalNum = result.length;
                })
            },
            // 处理每一行的关闭请求
            // closeHost(row){
            //   //   alert(row.hostid);
            //     this.$confirm('是否确认关闭主机'+row.name, '提示', {
            //         confirmButtonText: '确定',
            //         cancelButtonText: '取消',
            //         type: 'warning'
            //     }).then(() => {
            //         this.$message({
            //             type: 'success',
            //             message: '关闭成功!'
            //         });
            //     }).catch(() => {
            //         this.$message({
            //             type: 'info',
            //             message: '已取消关闭'
            //         });
            //     });
            // },

            closeHost(row){
              //   alert(row.hostid);
              const _this = this;
              this.$confirm('是否确认关闭主机'+row.name, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                // this.$message({
                //   type: 'success',
                //   message: '关闭成功!'
                // });

                // 通过主机id查询账户信息
                axios.get('host/getUserInfo.action?hostid='+row.hostid).then((res) => {
                  //console.log(res.data)
                  if (res.data.status){
                    _this.hostAccount = res.data.content.username
                    _this.hostPassword = res.data.content.password
                    _this.dialogVisible = true;    // 显示对话框
                    _this.operatedId = row.hostid  // 赋值要操作的ID
                    _this.operateCode = "0"
                  }
                  else {
                    this.$message({
                      type: 'error',
                      message: '该用户未设置用户名与密码，请前往设置'
                    });
                  }
                }).catch( () => {
                  console.error(res.data)
                })
              }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消关机'
                });
              });
            },
            // 重启服务器
            rebootHost(row){
                const _this = this;
                this.$confirm('是否确认重启主机'+row.name, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                  axios.get('host/getUserInfo.action?hostid='+row.hostid).then((res) => {
                    console.log(res.data.content)
                    if (res.data.status){
                      _this.hostAccount = res.data.content.username
                      _this.hostPassword = res.data.content.password
                      _this.dialogVisible = true;    // 显示对话框
                      _this.operatedId = row.hostid  // 赋值要操作的ID
                      _this.operateCode = "1"
                    }
                    else {
                      this.$message({
                        type: 'error',
                        message: '该用户未设置用户名与密码，请前往设置'
                      });
                    }
                  }).catch( () => {
                    console.error(res.data)
                  })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消重启'
                    });
                });
            },
            handleSubmit() {
                const _this = this
                axios({
                    method: 'get',
                    url: '/demo/get_pageable_online_host.action',
                    params: {
                        currentPage: _this.currentPage,
                        pageSize: _this.pageNum
                    }
                }).then((res) => {
                    // console.log("res:  "+res.data.content.result);
                    this.pictLoading = false
                    if (res.data.content.result == null) {
                        _this.tableData = [];
                    } else {
                        _this.tableData = res.data.content.result;
                    }
                })
            },
            handleSizeChange(val) {
                this.pageNum = val;
                this.handleSubmit();
            },
            handleCurrentChange(val) {
                this.currentPage = val;
                this.handleSubmit();
            },

            // 获取主机列表
            getHostList() {
                let _this = this;
                axios({
                    method: 'get',
                    url: '/demo/get_all_online_host.action'
                }).then(function (response) {
                    let resultList = response.data.content.result
                    _this.online_host_list = resultList;
                    _this.tableData = resultList;
                    console.log(_this.online_host_list);
                }).catch(function (error) {
                    console.log(error)
                })
            },
            // 关闭主机
            // shutdownHost() {
            //     // 遍历所有选中的主机
            //     for(let i = 0; i < this.$refs.hostList.selection.length; i++){
            //         console.log("主机："+this.$refs.hostList.selection[i].hostid);
            //     }
            // },

            // 主要的请求方法

            // 发送关机请求
            postShutdownRequest(){
              let _this = this;
              // 设置正在处理，让用户有所感知
              const loading = this.$loading({
                lock: true,
                text: '正在处理',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)'
              });

              axios({
                method: 'get',
                url: '/host_management/send_shutdown_to_host.action',
                params: {
                  hostId: _this.operatedId,
                  account: _this.hostAccount,
                  password: _this.hostPassword
                }
              }).then((res) => {
                loading.close();
                this.dialogVisible = false;
                this.$message({
                  type: 'success',
                  message: '关机成功'
                });
              }).catch(() => {
                loading.close();
                this.dialogVisible = false;
                this.$message({
                  type: 'error',
                  message: '关机失败，目标主机尚不支持关机或账号密码错误'
                });
              });
            },

            // 发送重启请求
            postRebootRequest(){
                let _this = this;
                // 设置正在处理，让用户有所感知
                const loading = this.$loading({
                    lock: true,
                    text: '正在处理',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });

                axios({
                    method: 'get',
                    url: '/host_management/send_reboot_to_host.action',
                    params: {
                        hostId: _this.operatedId,
                        account: _this.hostAccount,
                        password: _this.hostPassword
                    }
                }).then((res) => {
                  loading.close();
                  this.dialogVisible = false;
                  this.$message({
                    type: 'success',
                    message: '重启成功'
                  });
                }).catch(() => {
                    loading.close();
                    this.dialogVisible = false;
                    this.$message({
                        type: 'error',
                        message: '重启失败，目标主机尚不支持重启或账号密码错误'
                    });
                })
            },

          handleInput() {
            return this.tableData.filter(item => item.host.includes(this.queryString) || item.hostid.includes(this.queryString))
          },
        },
        mounted() {
            this.setTotalNum();
            this.handleSubmit();
        },

    }
</script>

<style scoped>
    .content{
        margin-top: 80px;
        width: 100%;
        height: 550px;
        overflow-x:hidden
    }
</style>
